import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    addresInfo: null,
    cart: [],
    // 没有公司的appid账号获取不到token -----此处模拟
    isLogin: false
  }
  methods = {

    // 提交订单--发起支付
    async onSubmit() {
      /*  模拟跳转
        wepy.navigateTo({
           url:'/pages/orderlist'
         }) */
      // 第一部：判断金额 判断收获地址
      if (this.amount <= 0) return wepy.baseToast('订单金额不能为0！')
      if (this.addressStr.length < 0) return wepy.baseToast('请选择收获地址')
      // 第二部： 创建订单 
      const { data: createResult } = await wepy.post('/my/orders/create', {
        // 订单金额元 先写死
        order_price: '0.01',
        consignee_addr: this.addressStr,
        order_detail: JSON.stringify(this.cart),
        goods: this.cart.map(x => {
          return {
            goods_id: x.id,
            goods_number: x.count,
            goods_price: x.price
          }
        })
      })
      // 创建订单失败
      if (createResult.meta.status != 200) return wepy.baseToast('模拟创建订单失败！')
      // 创建成功
      const orderInfo = createResult.message

      // console.log(orderInfo)
      //第三部 生产预支付订单--发请求
      const { data: orderResult } = await wepy.post('/my/orders/req_unifiedorder', {
        order_number: orderInfo.order_number
      })
      // 生产预支付订单失败
      if (orderResult.meta.status !== 200) return wepy.baseToast('生产预支付订单失败')

      //第四部 走支付流程--调微信支付api
      // console.log(orderResult);
      const payResul = await wepy
        .requestPayment(orderResult.message.pay)
        .catch(err => err)
      //用户取消了支付
      if (payResul.errMsg === 'requestPayment:fail cansel') return wepy.baseToast('你已取消了支付')
      // 第五部 检查支付结果
      const { data: payCheckResult } = await wepy.post('/my/orders/chkOrder', {
        order_number: orderInfo.order_number
      })
      if (payCheckResult.meta.status !== 200) return wepy.baseToast('订单未支付')
      //提示用户支付成功
      wepy.baseToast('支付成功！',success)
      //跳转到订单支付列表页面
      wepy.navigateTo({
        url: '/pages/orderlist'
      })
    },
    // 模拟登入
    chagneIslogin() {
      // 1.发起登入请求
      // 2.持久化存储token

      wepy.baseToast('模拟登入成功', 'none')
      this.isLogin = true
    },
    // 获取用户登入信息
    async getUserInfo(userInfo) {
      if (userInfo.detail.errMsg != 'getUserInfo:ok') return wepy.baseToast('获取用户信息失败')
      var { encryptedData: encryptedData, iv: iv, rawData: rawData, signature: signature } = userInfo.detail
      var res = await wepy.login()
      if (res.errMsg != "login:ok") return wepy.baseToast('获取登入信息失败')
      var { data: temp } = await wepy.post('/users/wxlogin', {
        code: res.code,
        encryptedData,
        iv,
        rawData,
        signature
      })
      console.log(temp);
      if (temp.meta.status != 200) return wepy.baseToast('登入失败')

    },
    async  chooseAddress() {
      var res = await wepy.chooseAddress().catch(err => err)
      if (res.errMsg != 'chooseAddress:ok') return;
      this.addresInfo = res;
      wepy.setStorageSync('address', res)
      this.$apply();
    }
  }
  onLoad() {
    this.addresInfo = wepy.getStorageSync('address') || null
    var newArr = this.$parent.globalData.cart.filter(i => i.isCheck)
    this.cart = newArr
  }
  computed = {
    isHavaAddress() {
      if (this.addresInfo === null) return false
      return true
    },
    addressStr() {
      if (this.addresInfo == null) return ''
      var { provinceName: a, cityName: b, countyName: c, detailInfo: d } = this.addresInfo
      return a + b + c + d
    },
    amount() {
      var total = 0;
      this.cart.forEach(element => {
        // 精度问题
        if (element.isCheck) total += element.price * 100 * element.count
      });
      return total
    }
  }
}